package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyWeiYing;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeWeiYing;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 全流程文档：微银信用全流程MD5
 * https://www.showdoc.com.cn/2598841380689709/11558777852579933
 * 密码：yxt123
 *
 * @author 李源聪
 * @since 2025/5/21 17:13
 */
@ApiPlan(productId = "210", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatWeiYingPhoneMd5 implements ApiPlatformPhoneMd5ConvertHandler {
    private static final String KEY = "94fyKLwJ0w6h8576";
    private static final String ORG_ID = "202305613";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        // 实体类
        ApiPlatDataExchangeWeiYing data = new ApiPlatDataExchangeWeiYing();
        //拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 获取加密的key
        data.setAppKey(KEY);
        // 获得手机号,小写
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        //  年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 1男 2女 0 未知
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "2", 0)
                .end(0);
        data.setGender(sex);
        //  城市名称
        data.setCity(apiDataExchangeParameter.getCity());
        // 城市编码
        data.setCityCode(apiDataExchangeParameter.getAreaCode());
        // 贷款时间 2(6个月)3(12个月)4(24个月)5(36个月)
        Integer time = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业 1:上班族 2:自由职业 3:企业主 4:公务员/国企
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 2)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1(600-650)2(650-700)3(700以上)4(无)5(600以下)
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 5)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 3)
                .end(4);
        data.setZhima(zhima);
        //  公积金 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 4)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 4)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        // 商业保险 0(6个月以下 )，1(6-12个月 )， 2(12个月以上)，3(无 )
        Integer commericalInsurance = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 4)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 0)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(4);
        data.setCommericalInsurance(commericalInsurance);

        //  房产 1:有 2:无
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        // 逾期记录1(信用良好)2(当前逾期中)
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(2);
        data.setOverdue(overdue);
        //  车产 1:有 2:无
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度 1:30000 2:50000 3:100000 4.200000
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 2)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setLoanAmount(money);
        // key
        data.setAppKey(KEY);
        // 上游渠道id
        data.setUserSourceFlag(apiDataExchangeParameter.getReqId());
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", dataStr);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyWeiYing data = new ApiPlatApplyWeiYing();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 撞库返回的id
        data.setOrderId(apiApplyParameter.dataExchangeApplyId());
        // 姓名
        data.setName(apiApplyParameter.getUserName());
        // 手机号
        data.setPhone(apiApplyParameter.getPhone());
        //  城市名称
        data.setCity(apiApplyParameter.getCity());
        // 城市编码
        data.setCityCode(apiApplyParameter.getAreaCode());
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 1男 2女 0 未知
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "2", 0)
                .end(0);
        data.setGender(sex);
        // 贷款时间 2(6个月)3(12个月)4(24个月)5(36个月)
        Integer time = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "2", 2)
                .when(apiApplyParameter.getLoanTerm(), "3", 3)
                .when(apiApplyParameter.getLoanTerm(), "4", 4)
                .when(apiApplyParameter.getLoanTerm(), "5", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业 1:上班族 2:自由职业 3:企业主 4:公务员/国企
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 2)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1(600-650)2(650-700)3(700以上)4(无)5(600以下)
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 5)
                .when(apiApplyParameter.getSesameCredit(), "2", 1)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 3)
                .end(4);
        data.setZhima(zhima);
        //  公积金 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 4)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 4)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        // 商业保险 0(6个月以下 )，1(6-12个月 )， 2(12个月以上)，3(无 )
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 4)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 0)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(4);
        data.setCommericalInsurance(commericalInsurance);

        //  房产 1:有 2:无
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        // 逾期记录1(信用良好)2(当前逾期中)
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(2);
        data.setOverdue(overdue);
        //  车产 1:有 2:无
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 2)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度 1:30000 2:50000 3:100000 4.200000
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 2)
                .when(apiApplyParameter.getLoanAmount(), "3", 3)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setLoanAmount(money);
        // key
        data.setAppKey(KEY);
        // 平台授权协议
        data.setAgreeProtocol(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        data.setUserSourceFlag(apiApplyParameter.getReqId());
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", dataStr);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");

        BigDecimal price = resData.getBigDecimal("price");
        String orderId = resData.getString("orderId");
        String productName = resData.getString("productName");
        String logo = resData.getString("productLogo");
        String companyName = resData.getString("companyName");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            //  获取协议
            JSONArray listProtocolResult = resData.getJSONArray("protocolList");
            IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                ApiProtocol protocol = new ApiProtocol();
                protocol.setProtocolName(protocolObject.getString("protocolName"));
                protocol.setProtocolUrl(protocolObject.getString("protocolValue"));
                newList.add(protocol);
            });
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setProtocolList(protocolList);
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setApplyId(orderId);
        result.setDisplayName(productName);
        result.setProductName(productName + "-" + companyName + "-上海运棋科技有限公司");
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
